package com.example.netty.handle;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Objects;

/**
 * @author PC
 */
public class SimpleChatServerHandle extends SimpleChannelInboundHandler<String> {

    private final static Logger logger = LoggerFactory.getLogger(SimpleChatServerHandle.class);

    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        logger.info(channel.remoteAddress() + " 加入\n");
        channelGroup.writeAndFlush(channel.remoteAddress() + " 加入\n");
        channelGroup.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        logger.info(channel.remoteAddress() + " 离开\n");
        channelGroup.writeAndFlush(channel.remoteAddress() + " 离开\n");
        channelGroup.remove(channel);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        Channel channel = ctx.channel();
        channel.writeAndFlush("[你说]" + msg + "\n");
        channelGroup.stream().filter(itemChannel -> !Objects.equals(channel, itemChannel))
                .forEach(itemChannel -> itemChannel.writeAndFlush(channel.remoteAddress() + ":" + msg + "\n"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel channel = ctx.channel();
        logger.error(channel.remoteAddress() + "异常:", cause);
        ctx.close();
    }
}
